<template>
  <div
    v-loading="loading || getDepartmentOptionsLoading"
    class="order_module"
    element-loading-text="加载中..."
  >
    <div class="header">
      <div class="btn_group">
        <HPlainButton @click="addData"> 添加模块 </HPlainButton>
        <el-dropdown trigger="click">
          <HButton :disabled="selecttion.length == 0">
            批量操作
            <el-icon class="el-icon--right">
              <ArrowDown />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="changeStatus(1)">
                <el-icon>
                  <CircleCheck />
                </el-icon>
                批量启用
              </el-dropdown-item>
              <el-dropdown-item @click="changeStatus(2)">
                <el-icon>
                  <Warning />
                </el-icon>
                批量禁用
              </el-dropdown-item>
              <el-dropdown-item @click="changeStatus(3)">
                <el-icon>
                  <Delete />
                </el-icon>
                批量删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>

      <div class="search">
        <!-- 部门 -->
        <el-select v-model="departmentId" placeholder="请选择部门" clearable @change="getList">
          <el-option
            v-for="(option, optionIndex) in departmentOptions"
            :key="optionIndex"
            :label="option.name"
            :value="option.id"
          />
        </el-select>

        <!-- 模块类型 -->
        <el-select
          v-model="type"
          placeholder="请选择模块类型"
          filterable
          clearable
          @change="getList"
        >
          <el-option value="1" label="安装" />
          <el-option value="2" label="维修" />
          <el-option value="3" label="保养" />
          <el-option value="4" label="其他" />
        </el-select>
        <el-input
          v-model.trim="name"
          placeholder="名称搜索"
          clearable
          @keyup.enter="getList"
          @clear="getList"
        />
        <HButton type="primary" @click="getList">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </HButton>
        <h-button @click="onReset">
          <el-icon><RefreshRight /></el-icon>
          重置
        </h-button>
      </div>
    </div>

    <div class="table_container">
      <el-table
        ref="tableDom"
        :border="true"
        stripe
        resizable
        :data="tableData"
        height="100%"
        @selection-change="handleChange"
      >
        <!-- 选择 -->
        <el-table-column type="selection" width="50" fixed="left" :align="'center'" />

        <!-- 序号 -->
        <el-table-column type="index" label="序号" width="50" fixed="left" :align="'center'" />

        <!-- 模块名称 -->
        <el-table-column show-overflow-tooltip prop="name" label="模块名称" min-width="150">
          <template #default="scope">
            <HLink @click="handleModuleNameClick(scope.row.id)">
              {{ scope.row.name }}
            </HLink>
          </template>
        </el-table-column>

        <!-- 模块类型 -->
        <el-table-column prop="type" label="模块类型" width="74">
          <template #default="scope">
            <span v-if="scope.row.type == 1">安装</span>
            <span v-if="scope.row.type == 2">维修</span>
            <span v-if="scope.row.type == 3">保养</span>
            <span v-if="scope.row.type == 4">其他</span>
          </template>
        </el-table-column>

        <!-- 质保状态 -->
        <el-table-column prop="overinsured" label="质保状态" width="74">
          <template #default="scope">
            <span v-if="!scope.row.overinsured">保内</span>
            <span v-if="scope.row.overinsured">保外</span>
          </template>
        </el-table-column>

        <!-- 保内费用 -->
        <el-table-column show-overflow-tooltip prop="inSourcingPrice" label="保内费用" width="100">
          <template #default="scope">
            <span>￥{{ scope.row.inSourcingPrice }}</span>
          </template>
        </el-table-column>

        <!-- 保外费用 -->
        <el-table-column show-overflow-tooltip prop="outSourcingPrice" label="保外费用" width="100">
          <template #default="scope">
            <span>￥{{ scope.row.outSourcingPrice }}</span>
          </template>
        </el-table-column>

        <!-- 移动端报单可见 -->
        <el-table-column
          show-overflow-tooltip
          prop="mobileCreateOrderShow"
          label="移动端报单可见"
          width="110"
        >
          <template #default="scope">
            <span v-if="scope.row.mobileCreateOrderShow">显示</span>
            <span v-else>隐藏</span>
          </template>
        </el-table-column>

        <!-- 质保工单 -->
        <el-table-column
          show-overflow-tooltip
          prop="enableWarrantyOrder"
          label="质保工单"
          width="74"
        >
          <template #default="scope">
            <span v-if="scope.row.enableWarrantyOrder">启用</span>
            <span v-else>禁用</span>
          </template>
        </el-table-column>

        <!-- 质保周期 -->
        <el-table-column show-overflow-tooltip prop="warrantyDay" label="质保周期" width="74">
          <template #default="scope">
            <span>{{ scope.row.warrantyDay }}天</span>
          </template>
        </el-table-column>

        <!-- 拨打电话类型 -->
        <el-table-column
          show-overflow-tooltip
          prop="callPhoneType"
          label="拨打电话类型"
          width="100"
        >
          <template #default="scope">
            <span v-if="scope.row.callPhoneType === 0">关闭</span>
            <span v-else>必须拨打</span>
          </template>
        </el-table-column>

        <!-- 结单核销码 -->
        <el-table-column
          show-overflow-tooltip
          prop="enableStatementVerifCode"
          label="结单核销码"
          width="86"
        >
          <template #default="scope">
            <span v-if="scope.row.enableStatementVerifCode">启用</span>
            <span v-else>禁用</span>
          </template>
        </el-table-column>

        <!-- 结单核销码类型 -->
        <el-table-column label="结单核销码类型" prop="statementVerifCodeType" width="110">
          <template #default="scope">
            {{ scope.row.statementVerifCodeType == 1 ? '随机' : '固定' }}
          </template>
        </el-table-column>

        <!-- 分配客服 -->
        <el-table-column label="分配客服" prop="autoDispatchClient" width="130">
          <template #default="scope">
            <span v-if="scope.row.autoDispatchClient">按规则自动分配</span>
            <span v-else>客服人工分配</span>
          </template>
        </el-table-column>

        <!-- 分配客服规则 -->
        <el-table-column
          show-overflow-tooltip
          label="分配客服规则"
          prop="workClientStrategy"
          width="150"
        />

        <!-- 分派网点 -->
        <el-table-column label="分派网点" prop="autoDispatchNetwork" width="130">
          <template #default="scope">
            <span v-if="scope.row.autoDispatchNetwork">按规则自动派单</span>
            <span v-else>网点人工分派</span>
          </template>
        </el-table-column>

        <!-- 预约时间 -->
        <el-table-column prop="reservationTimeType" label="预约时间" width="100">
          <template #default="scope">
            <span v-if="scope.row.reservationTimeType == 1">不启用</span>
            <span v-if="scope.row.reservationTimeType == 2">24小时</span>
            <span v-if="scope.row.reservationTimeType == 3">预约时间范围</span>
          </template>
        </el-table-column>

        <!-- 报单路径 -->
        <el-table-column show-overflow-tooltip prop="path" label="报单路径" width="400" />

        <!-- 创建时间 -->
        <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="128" />

        <!-- 更新时间 -->
        <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="128" />

        <!-- 状态 -->
        <el-table-column prop="status" label="状态" width="70" fixed="right" :align="'center'">
          <template #default="scope">
            <div class="flex_justify_center">
              <HStatus v-if="!scope.row.status">启用</HStatus>
              <HStatus v-if="scope.row.status" type="info">禁用</HStatus>
            </div>
          </template>
        </el-table-column>

        <!-- 操作 -->
        <el-table-column fixed="right" label="操作" width="90">
          <template #default="scope">
            <el-space :size="0" :spacer="spacer">
              <HLink @click="handleEditModule(scope.row.id)">编辑</HLink>
              <HLink type="error" @click="handleDelOrderModule(scope.row)">删除</HLink>
            </el-space>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <EditOrModuleModal
      :mode="modalMode"
      :title="modalTitle"
      :module-id="currentEditModuleId"
      :loading="dialogLoading"
      :visible="modalVisible"
      :is-show-del-btn="false"
      @delete="changeStatus(4)"
      @close="modalVisible = false"
      @updated="getList"
    />

    <!-- 分页 -->
    <div class="pagination">
      <Pagination
        ref="pagination"
        :list_total="total"
        @size-change="getList"
        @current-change="getList(false)"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, h, onMounted } from 'vue'
  import { Search, Warning, Delete, CircleCheck, ArrowDown } from '@element-plus/icons-vue'
  import { ElDivider, ElMessage, ElMessageBox, TableInstance } from 'element-plus'
  import Pagination from '@/components/Pagination/index.vue'
  import EditOrModuleModal from './EditOrModuleModal.vue'
  import { useRouter } from 'vue-router'
  import { moduleGetList, moduleDisable, moduleDelete } from '@/api/basic'
  import { OrderModule } from './types'
  import { useGetDepartmentOptions } from '@/services/module/department/useOptions'

  const {
    options: departmentOptions,
    getOptionsLoading: getDepartmentOptionsLoading,
    getOptions: getDepartmentOptions,
  } = useGetDepartmentOptions()

  const handleDelOrderModule = (orderModule: OrderModule) => {
    if (tableDom.value) {
      tableDom.value.clearSelection()
      tableDom.value.toggleRowSelection(orderModule, true)
      changeStatus(3)
    }
  }

  // 间距组件的间隔符
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })

  const router = useRouter()
  const loading = ref(false)
  const name = ref('') // 关键词
  const type = ref('') // 模块类型

  // 部门id
  const departmentId = ref('')

  const tableData = ref<Array<OrderModule>>([]) // 列表数据
  const tableDom = ref<TableInstance | null>(null) // 列表dom

  const pagination = ref() // 分页dom
  const total = ref(0) // 总数目

  // 当前编辑的模块的ID
  const currentEditModuleId = ref('-1')

  // 获取分页数据
  const getPageData = (val) => {
    if (val) pagination.value.setPage()
    return {
      limit: pagination.value.size,
      name: name.value,
      page: pagination.value.current,
      type: type.value,
      departmentId: departmentId.value,
    }
  }

  // 获取列表数据
  const getList = async (val = true) => {
    loading.value = true
    const res = await moduleGetList(getPageData(val))
    loading.value = false
    tableData.value = res.data.data.rows
    total.value = parseInt(res.data.data.total)
  }

  /**
   * 重置点击事件
   */
  const onReset = () => {
    name.value = ''
    type.value = ''
    departmentId.value = ''
    getList()
  }

  // 获取表格选中的数据
  const selecttion = ref([])

  // 弹窗模式：edit-编辑，add-添加
  const modalMode = ref<'edit' | 'add'>('edit')

  // 弹窗加载状态
  const dialogLoading = ref(false)

  // 弹窗标题
  const modalTitle = ref('编辑模块')

  // 弹窗的显示状态
  const modalVisible = ref(false)

  const handleChange = (val: any[]) => {
    if (val.length != 0) {
      val.forEach((item: { id: any }) => {
        if (Object.values(selecttion.value).indexOf(item.id) == -1) {
          selecttion.value.push(item.id)
        } else {
          selecttion.value = selecttion.value.filter((i) => i == item.id)
        }
      })
    } else {
      selecttion.value = []
    }
  }

  // 添加模块
  const addData = () => {
    modalMode.value = 'add'
    modalTitle.value = '添加模块'
    modalVisible.value = true
  }

  // 编辑模块
  const handleEditModule = (id: string) => {
    modalMode.value = 'edit'
    currentEditModuleId.value = id
    modalTitle.value = '编辑模块'
    modalVisible.value = true
  }

  // 模块名称点击事件
  const handleModuleNameClick = (id: string) => {
    router.push('/busic/base/moduleDetail/' + id)
  }

  // 修改状态方法
  const changeMethod = (type, method, arr, status, dialog) => {
    if (arr.length == 0) {
      ElMessage({
        message: `请选择要${type}的模块`,
        type: 'warning',
        duration: 5000,
        plain: true,
        showClose: true,
      })
      return
    }
    ElMessageBox({
      type: type == '删除' ? 'error' : 'warning',
      title: '提示',
      message: `确认${type}选中的模块?`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      draggable: true,
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    }).then(async () => {
      if (status != 3) {
        const res = await method(arr, status)
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 5000,
          plain: true,
          showClose: true,
        })
      } else {
        const res = await method(arr)
        if (res.data.success == true) {
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 5000,
            plain: true,
            showClose: true,
          })
        } else {
          ElMessage({
            message: res.data.message,
            type: 'warning',
            duration: 5000,
            plain: true,
            showClose: true,
          })
          return
        }
        if (dialog != '') {
          modalVisible.value = false
        }
      }
      selecttion.value = []
      tableDom.value.clearSelection()
      getList()
    })
  }

  // 批量启用/禁用/删除
  const changeStatus = (n) => {
    if (n == 1) {
      changeMethod('启用', moduleDisable, selecttion.value, false, '')
    }
    if (n == 2) {
      changeMethod('禁用', moduleDisable, selecttion.value, true, '')
    }
    if (n == 3) {
      changeMethod('删除', moduleDelete, selecttion.value, 3, '')
    }
    if (n == 4) {
      changeMethod('删除', moduleDelete, [currentEditModuleId.value], 3, modalVisible)
    }
  }
  onMounted(() => {
    getList()
    getDepartmentOptions()
  })
  defineExpose({ getList })
</script>

<style scoped lang="scss">
  @import '../../index.scss';
</style>
